{% extends "base.html" %}
{% load static %}
{% load i18n %}

{% block title %}{% trans "Instance" %} - {{ instance.name }}{% endblock %}

{% block page_heading %}
{{ instance.name }}{% if instance.title %} ({{ instance.title }}){% endif %}
{% endblock page_heading %}

{% block content %}
    {% include 'pleasewaitdialog.html' %}
    <!--block content-->
    <div class="page-header d-print-none">
        <div class="container-xl">
            <div class="row g-2 align-items-center">
                <div class="col">
                <h2 class="page-title">
                    {{ compute.name }}
                </h2>
                </div>
            </div>
        </div>
    </div>

    <div class="page-body">
        <div class="container-xl">
            <div class="card">
                {% if instance.status == 5 %}
                    <div class="ribbon ribbon-top bg-red"><!-- Download SVG icon from http://tabler-icons.io/i/star -->
                        <span class="badge bg-danger">{% trans "Off" %}</span>
                    </div>
                {% endif %}
                {% if instance.status == 1 %}
                    <div class="ribbon ribbon-top bg-green"><!-- Download SVG icon from http://tabler-icons.io/i/star -->
                        <span class="badge bg-success">{% trans "Active" %}</span>
                    </div>
                {% endif %}
                {% if instance.status == 3 %}
                    <div class="ribbon ribbon-top bg-yellow"><!-- Download SVG icon from http://tabler-icons.io/i/star -->
                        <span class="badge bg-warning">{% trans "Suspend" %}</span>
                    </div>
                {% endif %}
                <div class="card-header">
                    <h2 class="card-title">{{ instance.name }}</h2>
                </div>
                <div class="card-body">
                    <p class="text-muted">
                        <div class="row">
                            <div class="col-lg-4">
                                <dl class="row">
                                    <dt class="col-3">{% trans "VCPU" %}: </dt>
                                    {% if instance.cur_vcpu %}
                                        <dd class="col-9">{{ instance.cur_vcpu }}</dd>
                                    {% else %}
                                        <dd class="col-9">{{ instance.vcpu }}</dd>
                                    {% endif %}
                                    
                                    <dt class="col-3">{% trans "RAM" %}: </dt>
                                    <dd class="col-9">{{ instance.cur_memory }} {% trans "MB" %}</dd>

                                    <dt class="col-3">{% trans "Disk" %}: </dt>
                                    <dd class="col-9">
                                        {% for disk in instance.disks %}
                                            {{ disk.size|filesizeformat }}
                                        {% endfor %}
                                    </dd>
                                    <dt class="col-3">{% trans "IPv4" %}: </dt>
                                    <dd class="col-9">
                                        {% for net in instance.networks %}
                                            {% for ipv4 in net.ipv4 %}
                                                {{ ipv4 }} |
                                            {% endfor %}
                                        {% endfor %}
                                    </dd>
                                    <dt class="col-3">{% trans "Action" %}: </dt>
                                    <dd class="col-9">
                                        <a class="link-secondary" href="{% url 'instances:instance' instance.id %}" title="{% trans 'Refresh instance info' %}">
                                            <span class="fa fa-refresh"></span>
                                        </a>
                                        &nbsp;&nbsp;
                                        <a>
                                            <a class="nav-item dropdown" data-bs-toggle="dropdown">
                                                <span class="fa fa-power-off"></span>
                                            </a>
                                            {% if instance.status == 1 %}
                                                <div class="dropdown-menu">
                                                    <a class="dropdown-item">
                                                        <form action="{% url 'instances:poweroff' instance.id %}" method="post" role="form" aria-label0="Power off instance form">
                                                            {% csrf_token %}
                                                            <input type="submit" name="poweroff" class="btn btn-ghost-danger w-100 btn-sm" value="{% trans "Power Off" %}">
                                                        </form>
                                                    </a>
                                                    {% if request.user.is_superuser %}
                                                        <a class="dropdown-item">
                                                            <form action="{% url 'instances:suspend' instance.id %}" method="post" role="form" aria-label="Suspend instance form">{% csrf_token %}
                                                                <input type="submit" name="suspend" class="btn btn-ghost-warning w-100 btn-sm" value="{% trans "Suspend" %}">
                                                                <div class="clearfix"></div>
                                                            </form>
                                                        </a>
                                                    {% endif %}
                                                    <a class="dropdown-item">
                                                        <form action="{% url 'instances:powercycle' instance.id %}" method="post" role="form" aria-label="Power cycle instance form">{% csrf_token %}
                                                            <input type="submit" name="powercycle" class="btn btn-ghost-secondary w-100 btn-sm" value="{% trans "Power Cycle" %}">
                                                        </form>
                                                    </a>
                                                    <a class="dropdown-item">
                                                        <form action="{% url 'instances:force_off' instance.id %}" method="post" role="form" aria-label="Force to shutdown instance form">
                                                            {% csrf_token %}
                                                            <input type="submit" name="powerforce" class="btn btn-ghost-dark w-100 btn-sm" value="{% trans "Force Off" %}">
                                                        </form>
                                                    </a>
                                                </div>
                                            {% endif %}
                                            {% if instance.status == 3 %}
                                                <div class="dropdown-menu">
                                                    {% if request.user.is_superuser %}
                                                        <a class="dropdown-item">
                                                            <form action="{% url 'instances:resume' instance.id %}" method="post" role="form" aria-label="Resume instance from suspension form">{% csrf_token %}
                                                                <input type="submit" name="resume" class="btn btn-ghost-success w-100 btn-sm" value="{% trans "Resume" %}">
                                                            </form>
                                                        </a>
                                                        <a class="dropdown-item">
                                                            <form action="{% url 'instances:force_off' instance.id %}" method="post" role="form" aria-label="Force to shutdown form">{% csrf_token %}
                                                                <input type="submit" name="powerforce" class="btn btn-ghost-dark w-100 btn-sm" value="{% trans "Force Off" %}">
                                                            </form>
                                                        </a>
                                                    {% else %}
                                                        <a class="dropdown-item">
                                                            <form action="{% url 'instances:resume' instance.id %}" method="post" role="form" aria-label="Resume instance form">{% csrf_token %}
                                                                <input type="submit" class="btn btn-ghost-success w-100 btn-sm">{% trans "Resume" %}</button>
                                                            </form>
                                                        </a>
                                                    {% endif %}
                                                </div>
                                            {% endif %}
                                            {% if instance.status == 5 %}
                                                <div class="dropdown-menu">
                                                    <a class="dropdown-item">
                                                        <form action="{% url 'instances:poweron' instance.id %}" method="post" role="form" aria-label="Start instance form">
                                                            {% csrf_token %}
                                                            {% if instance.is_template %}
                                                                <p>{% trans "Template instance cannot be started." %}</p>
                                                                <input type="submit" name="poweron" class="btn btn-ghost-primary w-100 btn-sm" value="{% trans "Power On" %}">
                                                            {% else %}
                                                                <input type="submit" name="poweron" class="btn btn-ghost-primary w-100 btn-sm" onclick="showPleaseWaitDialog()" value="{% trans "Power On" %}">
                                                            {% endif %}
                                                        </form>
                                                    </a>
                                                </div>
                                            {% endif %}
                                        </a>
                                        &nbsp;&nbsp;
                                        <a class="link-secondary" href="{% url 'instances:destroy' instance.id %}" title="{% trans 'Destroy instance' %}">
                                            <span class="fa fa-trash"></span>
                                        </a>
                                    </dd>
                                    <dt class="col-12">{% trans "Remarks" %}: </dt>
                                    <dd class="col-12">
                                        <textarea rows="10" cols="30" disabled=true style="resize: none;">{{ instance.remarks }}</textarea>
                                    </dd>
                                </dl>
                            </div>
                            <div class="card col-lg-8">
                                <div class="row">
                                    <div id="tabs" class="list-group col-md-2 col-xs-4">
                                        <a tab="Access" href="#" class="tab list-group-item active">{% trans "Access" %}</a>
                                        <a tab="Resize" href="#" class="tab list-group-item">{% trans "Resize" %}</a>
                                        <a tab="Snapshot" href="#" class="tab list-group-item">{% trans "Snapshot" %}</a>
                                        <a tab="Settings" href="#" class="tab list-group-item">{% trans "Settings" %}</a>
                                        <a tab="Stats" href="#" class="tab list-group-item" id="graphics-tab" aria-controls="graphics" data-bs-toggle="pill" data-bs-target="#graphics" type="button">{% trans "Stats" %}</a>
                                    </div>
                                    <div class="col-md-10 col-xs-4">
                                        <div id="Access" class="tab-item">
                                            {% include 'instances/access_tab.html' %}
                                        </div>
                                        <div id="Resize" class="tab-item">
                                            {% include 'instances/resize_tab.html' %}
                                        </div>
                                        <div id="Snapshot" class="tab-item">
                                            {% include 'instances/snapshots_tab.html' %}
                                        </div>
                                        <div id="Settings" class="tab-item">
                                            {% include 'instances/settings_tab.html' %}
                                        </div>
                                        <div id="Stats" class="tab-item">
                                            {% include 'instances/stats_tab.html' %}
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </p>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
{% block script %}
<script src="{% static "assets/js/vendors/chart.bundle.min.js" %}"></script>
<script src="{% static 'js/ace/ace.js' %}" type="text/javascript" charset="utf-8"></script>
<script>
    function get_volumes(compute_id, pool) {
        get_vol_url = "/computes/" + compute_id + "/storage/" + pool + "/volumes";
        $.getJSON(get_vol_url, function (data) {
            $("#vols").find('option').remove();
            $("#vols").removeAttr("disabled");

            $.each(data['vols'], function(i, item) {
                $("#vols").append('<option value=' + item +'>' + item + '</option>');
            })
        });

        var sto_drop = document.getElementById('select_storage');
        sto_drop.value = pool;
        sto_drop.innerHTML = pool + "<span class=\"caret\"></span>";

        var sto_input = document.getElementById('selected_storage');
        sto_input.setAttribute('value', pool);
        //sto_input.innerHTML = pool;
    }
</script>
<script>
    var editor = ace.edit("editor");
    editor.getSession().setMode("ace/mode/xml");

    var input = $('input[name="inst_xml"]');
        editor.getSession().on("change", function () {
        input.val(editor.getSession().getValue());
    });
</script>
<script>
    function random_mac(net) {
        $.getJSON("{% url 'instances:random_mac_address' %}", function (data) {
            $('input[name="' + net + '"]').val(data['mac']);
        });
    }
</script>
<script>
    function show_console() {
        if ($('#console_show_pass').attr('type') == 'password') {
            $('#console_show_pass').attr('type', 'text');
        } else {
            $('#console_show_pass').attr('type', 'password');
        }
    }
</script>
<script>
    function guess_mac_address(src_elem, net) {
        new_vname = $(src_elem).val();
        guess_mac_address_url = "{% url 'instances:guess_mac_address' 1 %}".replace(1, new_vname);
        $.getJSON(guess_mac_address_url, function(data) {
            $('input[name="clone-net-mac-'+net+'"]').val(data['mac']);
        });
    }
</script>
<script>
    function guess_clone_name() {
        $.getJSON("{% url 'instances:guess_clone_name' %}", function(data) {
            guessed_name = data['name'].split(".")[0];
            $('#clone_name').val(guessed_name);
            update_clone_disk_name(guessed_name);
            guess_mac_address('#clone_name', 0);
        });
    }
</script>
<script>
    function update_clone_disk_name(new_vname) {
        vname = '{{ instance.name }}';
        {% for disk in instance.disks %}
            disk_name = '{{ disk.image }}';
            disk_dot = disk_name.split('.');
            disk_dot_suffix = disk_dot[disk_dot.length-1];
            if (disk_name.startsWith(vname)) {
                image = disk_name.replace(vname, new_vname);
            } else if (disk_name.lastIndexOf('.') > -1 && disk_dot_suffix.length <= 7) {
                disk_dot.pop();
                disk_name_only = disk_dot.join('-');
                image = new_vname + "-" + disk_name_only + "." + disk_dot_suffix
            } else if (new_vname != disk_name) {
                image = new_vname
            } else {
                image = new_vname + '-clone';
            }
            $('#disk_name-{{ disk.dev }}').val(image);
        {% endfor %}
    }
</script>
<script>
    $(document).on('change', '#console_passwd_gen', function () {
        if ($(this).prop('checked')) {
            $('#console_passwd_manual').hide();
            $('#console_passwd_clear').prop('checked', false);
        } else {
            $('#console_passwd_manual').show();
        }
    });
    $(document).on('change', '#console_passwd_clear', function () {
        if ($(this).prop('checked')) {
            $('#console_passwd_manual').hide();
            $('#console_passwd_gen').prop('checked', false);
        } else {
            $('#console_passwd_manual').show();
        }
    });
    $(document).on('change', '#console_keymap_clear', function () {
        if ($(this).prop('checked')) {
            $('#console_keymap_selection').hide();
        } else {
            $('#console_keymap_selection').show();
        }
    });
    $('#clone_name').on('input', function () {
        update_clone_disk_name($(this).val());
    });
    $(document).ready(function () {
        // set current console keymap or fall back to default
        var keymap = "{{ instance.console_keymap }}";
        if (keymap != '') {
            $("#console_select_keymap option[value='" + keymap + "']").prop('selected', true);
        }
    });
    $(document).ready(function () {
        // set current console type or fall back to default
        var console_type = "{{ instance.console_type }}";
        if (console_type != '') {
            $("#console_select_type option[value='" + console_type + "']").prop('selected', true);
        }
    });
    $(document).ready(function () {
        // set current console listen address or fall back to default
        var console_listener_address = "{{ instance.console_listener_address }}";
        if (console_listener_address != '') {
            $("#console_select_listener_address option[value='" + console_listener_address + "']").prop('selected', true);
        }
    });
    $(document).ready(function () {
        // get video model or fall back to default
        let video_model = "{{ instance.video_model }}";
        if (video_model != '') {
            $("#video_model_select option[value='" + video_model + "']").prop('selected', true);
        }
    });
    $(document).ready(function () {
        // set vdi url
        $.get("{% url 'vdi_url' compute.id instance.name %}", function(data) {
            $("#vdi_url_input").attr("value", data);
            $("#vdi_url").attr("href", data);
        });
    });
{% if request.user.is_superuser %}
    $(document).ready(function () {
        random_mac('clone-net-mac-0');
        random_mac('add-net-mac');
        update_clone_disk_name($('#clone_name').val());
    });
{% else %}
    $('#select_clone_name').on('change', function () {
        update_clone_disk_name($(this).val());
        guess_mac_address('#select_clone_name', 0);
    });
    $(document).ready(function () {
        update_clone_disk_name($('#select_clone_name').val());
        guess_mac_address('#select_clone_name', 0);
    });
{% endif %}
</script>
<script>
    $(document).ready(function(){
        $('[data-bs-toggle="popover"]').popover({
            placement : 'top'
        });
    });
</script>
<script>
    function set_orderlist(obj){
        var result = '';
        $('#b_order label input:checked').each(function () {
            if (result != '') result += ',';
            result += $(this).val();
        });
        obj.val(result);
    }
    $(document).ready(function () {
    {# Boot Order Arragements #}
    jQuery.fn.multiselect = function() {
        $(this).each(function() {
            var checkboxes = $(this).find("input:checkbox");
            checkboxes.each(function() {
                var checkbox = $(this);
                // Highlight pre-selected checkboxes
                if (checkbox.prop("checked"))
                    checkbox.parent().addClass("multiselect-on");
                // Highlight checkboxes that the user selects
                checkbox.click(function() {
                    if (checkbox.prop("checked"))
                        checkbox.parent().addClass("multiselect-on");
                    else
                        checkbox.parent().removeClass("multiselect-on");
                });
            });
        });
    };
    $(function() {
     $(".multiselect").multiselect();
    });

    $('#boot_order_up').bind('click', function() {
        $('#b_order label input:checked').each( function() {
            var label = $(this).parent();
            var newPos = label.index() - 1;
            if (newPos > -1) {
                 $('#b_order label').eq(newPos).before("<label><input type='checkbox' value='"+$(this).val()+"' name='"+$(this).val()+"' checked>"+$(this).parent().text()+"</label>");
                 label.remove();
            }
            $(".multiselect").multiselect();
        });
        set_orderlist($("#bootorder"));
    });

    $('#boot_order_down').bind('click', function() {
        var countOptions = $('#b_order label').length;
        var countSelected = $('#b_order label input:checked').length;
        $('#b_order label input:checked').each( function() {
            var label = $(this).parent();
            var newPos = label.index() + countSelected;
            if (newPos < countOptions) {
                $('#b_order label').eq(newPos).after("<label><input type='checkbox' value='"+$(this).val()+"' name='"+$(this).val()+"' checked>"+$(this).parent().text()+"</label>");
                label.remove();
            }
            $(".multiselect").multiselect();
        });
       set_orderlist($("#bootorder"));
    });
});
</script>
<script>
    $(function () {
        $('.js-custom__checkbox').change(function () {
            var container  = $(this).closest('.js-custom__container');
            var toggles    = container.find('.js-custom__toggle');
            toggles.toggle();
        });
    });
</script>
<script>
    var stats_tab = document.querySelector('#graphics-tab');
    stats_tab.addEventListener('shown.bs.tab', function (event) {
        var cpu_ctx = $("#cpuChart").get(0).getContext("2d");
        var cpuChart = new Chart(cpu_ctx, {
            type: 'line',
            data: {
                datasets : [{
                    backgroundColor: "rgba(44,127,184,0.5)",
                    label: "Usage"
                }]
            },
            options: {
                responsive: true,
                legend: {
                    display: false
                },
                scales: {
                    xAxes:[{
                        offset: false,
                        ticks: {
                            beginAtZero: false,
                            autoSkip: true,
                            maxTicksLimit: 10,
                            maxRotation: 0,
                            minRotation: 0,
                            stepSize: 10,
                        },
                    }],
                    yAxes: [{
                        ticks: {
                            suggestedMax: 100,
                            suggestedMin: 0,
                            stepSize: 20,
                            callback: function(value, index, values) {
                                return value + ' %';
                            }
                        },
                    }],
                },
                tooltips: {
                     callbacks: {
                         label: function (tooltipItem, chart) {
                             var label = chart.datasets[tooltipItem.datasetIndex].label || '';
                             if (label) {
                                label += ': ';
                             }
                             return label += tooltipItem.yLabel + ' %';
                         }
                     }
                }
            }
        });

        var mem_ctx = $("#memChart").get(0).getContext("2d");
        var memChart = new Chart(mem_ctx, {
            type: 'line',
            data: {
                datasets : [{
                    label: "Usage"
                }]
            },
            options: {
                responsive: true,
                legend: {
                    display: false
                },
                scales: {
                    xAxes:[{
                        offset: false,
                        ticks: {
                            beginAtZero: false,
                            autoSkip: true,
                            maxTicksLimit: 10,
                            maxRotation: 0,
                            minRotation: 0,
                            stepSize: 10,
                        },
                    }],
                    yAxes: [{
                        ticks: {
                            suggestedMax: 100,
                            suggestedMin: 0,
                            stepSize: 20,
                            callback: function(value, index, values) {
                                return value + ' MB';
                            }
                        },
                    }],
                },
                tooltips: {
                     callbacks: {
                         label: function (tooltipItem, chart) {
                             var label = chart.datasets[tooltipItem.datasetIndex].label || '';
                             if (label) {
                                label += '(RSS): ';
                             }
                             return label += tooltipItem.yLabel + ' MB';
                         }
                     }
                }
            }
        });

        var diskChart = {};
        {% for disk in instance.disks %}
            var disk_ctx_{{ disk.dev }} = $("#blk{{ disk.dev }}Chart").get(0).getContext("2d");
            diskChart['{{ disk.dev }}'] = new Chart(disk_ctx_{{ disk.dev }}, {
                type: 'line',
                data: {
                    datasets : [{
                        backgroundColor: "rgba(127,205,187,0.5)",
                        label: "Read"
                    },
                    {
                        backgroundColor: "rgba(44,127,184,0.5)",
                        label: "Write"
                    }]
                },
                options: {
                    responsive: true,
                    legend: {
                        display: false
                    },
                    scales: {
                        xAxes:[{
                            offset: false,
                            ticks: {
                                beginAtZero: false,
                                autoSkip: true,
                                maxTicksLimit: 10,
                                maxRotation: 0,
                                minRotation: 0,
                                stepSize: 10,
                            },
                        }],
                        yAxes: [{
                            ticks: {
                                suggestedmax: 100,
                                suggestedMin: 0,
                                callback: function(value, index, values) {
                                    return value + ' Mb/s';
                                }
                            },
                        }],
                    },
                    tooltips: {
                         callbacks: {
                             label: function (tooltipItem, chart) {
                                 var label = chart.datasets[tooltipItem.datasetIndex].label || '';
                                 if (label) {
                                    label += ': ';
                                 }
                                 return label += tooltipItem.yLabel + ' Mb/s';
                             }
                         }
                    }
                }
            });
        {% endfor %}

        var netChart = {};
        {% for net in instance.networks %}
            var net_ctx_{{ forloop.counter0 }} = $("#netEth{{ forloop.counter0 }}Chart").get(0).getContext("2d");
            netChart[{{ forloop.counter0 }}] = new Chart(net_ctx_{{ forloop.counter0 }}, {
                type: 'line',
                data: {
                   datasets : [
                       {
                            backgroundColor: "rgba(127,205,187,0.5)",
                            label: "Inbound"
                       },
                       {
                            backgroundColor: "rgba(44,127,184,0.5)",
                            label: "Outbound"
                       }]
                },
                options: {
                    responsive: true,
                    legend: {
                        display: false
                    },
                    scales: {
                        xAxes:[{
                            offset: false,
                            ticks: {
                                beginAtZero: false,
                                autoSkip: true,
                                maxTicksLimit: 10,
                                maxRotation: 0,
                                minRotation: 0,
                                stepSize: 10,
                            },
                        }],
                        yAxes: [{
                            ticks: {
                                suggestedMax: 100,
                                suggestedMin: 0,
                                callback: function(value, index, values) {
                                    return value + ' Mbps';
                                }
                            },
                        }],
                    },
                    tooltips: {
                         callbacks: {
                             label: function (tooltipItem, chart) {
                                 var label = chart.datasets[tooltipItem.datasetIndex].label || '';
                                 if (label) {
                                    label += ': ';
                                 }
                                 return label += tooltipItem.yLabel + ' Mbps';
                             }
                         }
                    }
                }
            });
        {% endfor %}

        var graph_interval = window.setInterval(function graph_usage() {
            $.getJSON("{% url 'instances:stats' instance.id %}", function (data) {
                cpuChart.data.labels.push(data.timeline);
                cpuChart.data.datasets[0].data.push(data.cpudata);
                if (cpuChart.data.datasets[0].data.length > 10){
                    cpuChart.data.labels.shift();
                    cpuChart.data.datasets[0].data.shift();
                }
                cpuChart.update();

                memChart.data.labels.push(data.timeline);
                memChart.options.scales.yAxes[0].ticks.max = parseInt(data.memdata.total / 1024);
                memChart.options.scales.yAxes[0].ticks.stepSize = parseInt(data.memdata.total / (1024 * 5));
                memChart.data.datasets[0].data.push(data.memdata.used / 1024);
                if (memChart.data.datasets[0].data.length > 10){
                    memChart.data.labels.shift();
                    memChart.data.datasets[0].data.shift();
                }
                memChart.update();

                for (let j = 0; j < data.blkdata.length; j++) {
                    diskChart[data.blkdata[j].dev].data.labels.push(data.timeline);

                    diskChart[data.blkdata[j].dev].data.datasets[0].data.push(data.blkdata[j].data[0]);
                    diskChart[data.blkdata[j].dev].data.datasets[1].data.push(data.blkdata[j].data[1]);
                    if (diskChart[data.blkdata[j].dev].data.datasets[0].data.length > 10){
                        diskChart[data.blkdata[j].dev].data.labels.shift();
                        diskChart[data.blkdata[j].dev].data.datasets[0].data.shift();
                        diskChart[data.blkdata[j].dev].data.datasets[1].data.shift();
                    }
                    diskChart[data.blkdata[j].dev].update();
                }

                for (let j = 0; j < data.netdata.length; j++) {
                    netChart[data.netdata[j].dev].data.labels.push(data.timeline);

                    netChart[data.netdata[j].dev].data.datasets[0].data.push(data.netdata[j].data[0]);
                    netChart[data.netdata[j].dev].data.datasets[1].data.push(data.netdata[j].data[1]);
                    if (netChart[data.netdata[j].dev].data.datasets[0].data.length > 10){
                        netChart[data.netdata[j].dev].data.labels.shift();
                        netChart[data.netdata[j].dev].data.datasets[0].data.shift();
                        netChart[data.netdata[j].dev].data.datasets[1].data.shift();
                    }
                    netChart[data.netdata[j].dev].update();
                }
            });
        }, 10000);
    });
</script>
<script>
    backgroundJobRunning = false;
    var status_interval = window.setInterval(function get_status() {
        var status = {{ instance.status|lower }};
        $.getJSON("{% url 'instances:status' instance.id %}", function (data) {
            if (data['status'] != status && !backgroundJobRunning) {
                window.location.reload()
            }
        });
    }, 5000);

    // Stop getting status info before delete instance
    $('#delete_form').submit(function(){
        window.clearInterval(status_interval);
        return true;
    });
</script>
<script>
    var hash = location.hash;
    if (~$.inArray(hash, ['#poweron', '#poweroff', '#powercycle', '#suspend', '#resume'])) {
        var btnsect = $('#navbtn>li>a');
        $(btnsect).each(function () {
            if ($(this).attr('href') === '#power') {
                $(this).trigger('click');
            }
        });
    }
    if (~$.inArray(hash, ['#resize', "#resizevm_cpu", "#resizevm_mem", "#resizevm_disk"])) {
        var btnsect = $('#navbtn>li>a');
        $(btnsect).each(function () {
            if ($(this).attr('href') === '#resize') {
                $(this).trigger('click');
            }
        });
    }
    if (~$.inArray(hash, ['#osinfo', '#boot_opt', "#disks", '#network', '#clone', '#xmledit', '#vncsettings', '#migrate', '#options', '#users'])) {
        var btnsect = $('#navbtn>li>a');
        $(btnsect).each(function () {
            if ($(this).attr('href') === '#settings') {
                $(this).trigger('click');
            }
        });

        var btn = $('#settings>div>ul>li>a');
        $(btn).each(function () {
            if ($(this).attr('href') === hash) {
                $(this).trigger('click');
            }
        });
    }
    if (~$.inArray(hash, ['#takesnapshot', "#takeextsnapshot", "#managesnapshot"])) {
        var btnsect = $('#navbtn>li>a');
        $(btnsect).each(function () {
            if ($(this).attr('href') === '#snapshots') {
                $(this).trigger('click');
            }
        });

        var btn = $('#snapshots>div>ul>li>a');
        $(btn).each(function () {
            if ($(this).attr('href') === hash) {
                $(this).trigger('click');
            }
        });
    }
</script>
<script>
    function get_osinfo() {
        document.querySelector("#settings-tab").click();
        document.querySelector("#osinfo-tab").click();

        $.getJSON("{% url 'instances:osinfo' instance.id %}", function (data) {
            $.each(data, function() {
                $('#oshostname').text(data['host-name']);
                $('#osname').text(data.id);
                $('#osprettyname').text(data['pretty-name']);
                $('#oskernelrelease').text(data['kernel-release']);
                $('#oskernelversion').text(data['kernel-version']);
                $('#osversion').text(data.version);
                $('#ostimezone').text(data.zone + " / " + data.offset);
            })
        });
    }
</script>
<script>
    //事件委托给父级div来处理
    $(document).ready(function () {
        $(".tab-item").hide();
        $("#Access").show();
    });
    $(document).ready(function () {
        $("#tabs").on("click", "a", function (event) {
            let target = $(event.target);
            $(".tab-item").hide();
            $(".tab").removeClass("active");
            //添加css样式
            target.addClass("active");
            //取自定义字段里面的值(即a标签里面的tab字段)
            //tab字段里面存的是各个标签页的id, 以此来控制显示和隐藏
            $("#" + target.attr("tab")).show();
        });
    });
</script>
{% endblock %}
